package com.atguigu.consumer;

import com.alibaba.fastjson.JSON;
import com.atguigu.client.PaymentFeignClient;
import com.atguigu.constant.MqConst;
import com.atguigu.entity.OrderInfo;
import com.atguigu.entity.PaymentInfo;
import com.atguigu.enums.OrderStatus;
import com.atguigu.enums.PaymentStatus;
import com.atguigu.enums.ProcessStatus;
import com.atguigu.service.OrderInfoService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

@Component
public class OrderConsumer {
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private PaymentFeignClient paymentFeignClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    //1.超时未支付 自动取消订单
    @RabbitListener(queues = MqConst.CANCEL_ORDER_QUEUE)
    public void cancelOrder(Long orderId) {
        //根据订单id查询订单
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        //需要订单为未支付的情况下去关闭订单
        if (orderInfo != null && orderInfo.getProcessStatus().equals(OrderStatus.UNPAID.name())) {
            //修改订单状态为关闭状态
            orderInfoService.updateOrderStatus(orderInfo, ProcessStatus.CLOSED);
            //关闭支付订单 还需要编写一个关闭支付订单的接口
            PaymentInfo paymentInfo = paymentFeignClient.getPaymentInfo(orderInfo.getOutTradeNo());
            if (paymentInfo != null && paymentInfo.getPaymentStatus().equals(PaymentStatus.UNPAID.name())) {
                //如果要关闭支付订单
                rabbitTemplate.convertAndSend(MqConst.CLOSE_PAYMENT_EXCHANGE, MqConst.CLOSE_PAYMENT_ROUTE_KEY, orderId);
                //查询支付宝里面是否有交易记录
                boolean flag = paymentFeignClient.queryAlipayTrade(orderId);
                if (flag) {
                    //关闭支付宝记录
                    paymentFeignClient.closeAlipayTrade(orderId);
                }
            }
        }
    }

    //2.支付成功之后修改订单状态
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.PAY_ORDER_QUEUE, durable = "false"),
            exchange = @Exchange(value = MqConst.PAY_ORDER_EXCHANGE, durable = "false"),
            key = {MqConst.PAY_ORDER_ROUTE_KEY}
    ))
    public void updateOrderAfterPaySuccess(Long orderId, Message message, Channel channel) throws Exception {
        if (orderId != null) {
            //根据订单id查询订单信息
            OrderInfo orderInfo = orderInfoService.getOrderInfo(orderId);
            //当订单状态为未支付的时候修改订单
            if (orderInfo != null && PaymentStatus.UNPAID.name().equals(orderInfo.getProcessStatus())) {
                orderInfoService.updateOrderStatus(orderInfo, ProcessStatus.PAID);
                //通知库存系统减库存
                orderInfoService.sendMsgToWareHouse(orderInfo);
            }
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //3.仓库系统减库存成功之后的消费代码
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.SUCCESS_DECREASE_STOCK_QUEUE, durable = "false"),
            exchange = @Exchange(value = MqConst.SUCCESS_DECREASE_STOCK_EXCHANGE, durable = "false"),
            key = {MqConst.SUCCESS_DECREASE_STOCK_ROUTE_KEY}
    ))
    public void updateOrderStatus(String msgJson, Message message, Channel channel) throws Exception {
        if (!StringUtils.isEmpty(msgJson)) {
            //把json字符串转换为map
            Map<String, Object> map = JSON.parseObject(msgJson, Map.class);
            String orderId = (String) map.get("orderId");
            String status = (String) map.get("status");
            //如果仓库减库存成功 这边就把状态改为等待发货
            OrderInfo orderInfo = orderInfoService.getOrderInfo(Long.parseLong(orderId));
            if ("DEDUCTED".equals(status)) {
                orderInfoService.updateOrderStatus(orderInfo, ProcessStatus.WAITING_DELEVER);
            } else {
                orderInfoService.updateOrderStatus(orderInfo, ProcessStatus.STOCK_EXCEPTION);
            }
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }


}


